package org.feerepository.client.controller;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;
import java.util.ArrayList;
import java.util.List;
import org.feerepository.client.views.IServiceMapView;


public class ServiceListMapController  implements RequestCallback
{

   private static ServiceListMapController instance;
   private List<IServiceMapView> views = new ArrayList<IServiceMapView>();

   public void addView(IServiceMapView view)
   {
       views.add(view);
   }

    public static ServiceListMapController getInstance()
    {
        if(instance == null)
            instance = new ServiceListMapController();
        return instance;
    }

    public void onResponseReceived(Request request, Response response)
    {
      parseResponse(response.getText());
    }

    private void parseResponse(String response)
    {
        Document doc = XMLParser.parse(response);
        NodeList serviceMaps = doc.getElementsByTagName("servicemap");
        for(int i=0; i<serviceMaps.getLength();i++)
        {
            Element mapElement = (Element)serviceMaps.item(i);
            this.parseServiceMap(mapElement);
        }

    }
    private void parseServiceMap(Element serviceMap)
    {
            NodeList services =  serviceMap.getChildNodes();
            //for(int i=0;i< services.getLength();i++)
            {
             //   Element service = (Element) services.item(i);
                String name = serviceMap.getElementsByTagName("servicename").item(0).getFirstChild().getNodeValue();
                  for(IServiceMapView view: views)
                    {
                        view.addService(name);
                    }
            }
    }
    public void onError(Request request, Throwable exception) {
       // throw new UnsupportedOperationException("Not supported yet.");
    }

}
